package org.example;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class Main {
    private static boolean adminAuthenticated = false;
    private static String getPetNameById(int petId) throws SQLException {
    String sql = "SELECT name FROM pets WHERE id = ?";
    try (java.sql.Connection conn = JDBCDemo.getConnection();
         java.sql.PreparedStatement ps = conn.prepareStatement(sql)) {

        ps.setInt(1, petId);
        try (java.sql.ResultSet rs = ps.executeQuery()) {
            if (rs.next()) {
                return rs.getString("name");
            }
        }
    }
    return "未知宠物";
}
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        PetSelect selectService = new PetSelect();
        PetManager manager = new PetManager();

        while (true) {
            System.out.println("\n=== 宠物领养系统 ===");
            System.out.println("1. 查看所有可领养宠物");
            System.out.println("2. 按名字领养宠物");
            System.out.println("3. 查看领养记录");
            System.out.println("4. 按种类筛选宠物");
            System.out.println("5. 按价格范围筛选宠物");
            System.out.println("6. 添加新宠物");
            System.out.println("7. 修改宠物信息");
            System.out.println("0. 退出系统");
            System.out.print("请选择功能：");

            int choice = getIntInput(scanner);

            try {
                switch (choice) {
                    case 0:
                        System.out.println(" 欢迎下次光临！");
                        return;
                    case 1:
                        listAvailablePets(selectService);
                        break;
                    case 2:
                        adoptPetByName(manager, scanner);
                        break;
                    case 3:
                        viewAdoptionRecords(manager);
                        break;
                    case 4:
                        filterPetsByKind(scanner, selectService);
                        break;
                    case 5:
                        filterPetsByPriceRange(scanner, selectService);
                        break;
                    case 6:
                        handleAddPet(manager, scanner);
                        break;
                    case 7:
                        handleUpdatePet(manager, scanner);
                        break;
                    default:
                        System.out.println("输入错误，请输入数字。");
                }
            } catch (SQLException e) {
                System.err.println("数据库错误：" + e.getMessage());
            } catch (Exception e) {
                System.err.println("操作失败：" + e.getMessage());
            }
        }
    }

    private static int getIntInput(Scanner scanner) {
        while (!scanner.hasNextInt()) {
            System.out.print("请输入一个有效数字：");
            scanner.next();
        }
        int num = scanner.nextInt();
        scanner.nextLine();
        return num;
    }

    private static void listAvailablePets(PetSelect service) throws SQLException {
        List<Pet> pets = service.listAvailablePets();
        if (pets.isEmpty()) {
            System.out.println("暂无可领养宠物。");
        } else {
            System.out.println("\n=== 可领养宠物列表 ===");
            for (Pet pet : pets) {
                System.out.println(pet);
                System.out.println("-----------------------------");
            }
            System.out.println("共 " + pets.size() + " 只。");
        }
    }

    private static void adoptPetByName(PetManager manager, Scanner scanner) throws SQLException {
        System.out.print("请输入要领养的宠物名字：");
        String petName = scanner.nextLine().trim();

        if (petName.isEmpty()) {
            System.out.println("宠物名字不能为空！");
            return;
        }

        System.out.print("请输入您的姓名：");
        String name = scanner.nextLine().trim();

        System.out.print("请输入您的电话：");
        String phone = scanner.nextLine().trim();

        if (name.isEmpty() || phone.isEmpty()) {
            System.out.println("姓名和电话不能为空！");
            return;
        }

        manager.adoptPetByName(petName, name, phone);
        System.out.println("成功领养宠物 [" + petName + "]！");
    }
    private static void filterPetsByKind(Scanner scanner, PetSelect service) throws SQLException {
        System.out.print("请输入要筛选的宠物种类：");
        String kind = scanner.nextLine().trim();

        if (kind.isEmpty()) {
            System.out.println("种类不能为空！");
            return;
        }

        List<Pet> filteredPets = service.filterPetsByKind(kind);
        if (filteredPets.isEmpty()) {
            System.out.println("暂无符合条件的宠物。");
        } else {
            System.out.println("\n=== " + kind + " 类别下的可领养宠物 ===");
            for (Pet pet : filteredPets) {
                System.out.println(pet);
                System.out.println("-----------------------------");
            }
            System.out.println("共 " + filteredPets.size() + " 只。");
        }
    }
    private static void filterPetsByPriceRange(Scanner scanner, PetSelect selectService) {
        try {
            System.out.print("请输入最低价格：");
            int min = Integer.parseInt(scanner.nextLine().trim());
            System.out.print("请输入最高价格：");
            int max = Integer.parseInt(scanner.nextLine().trim());

            if (min > max) {
                System.out.println("最低价格不能高于最高价格！");
                return;
            }

            List<Pet> pets = selectService.filterPetsByPriceRange(min, max);
            if (pets.isEmpty()) {
                System.out.println("暂无该价格区间的可领养宠物。");
            } else {
                System.out.println("\n--- 符合条件的宠物 ---");
                for (Pet pet : pets) {
                    System.out.println(pet);
                }
            }
        } catch (NumberFormatException e) {
            System.out.println("价格必须是数字！");
        } catch (SQLException e) {
            System.err.println("数据库错误：" + e.getMessage());
        }
    }

    private static void viewAdoptionRecords(PetManager manager) {
        try {
            List<Map<String, String>> records = manager.getAdoptionRecords();
            if (records.isEmpty()) {
                System.out.println("暂无领养记录。");
            } else {
                System.out.println("\n--- 领养记录 ---");
                for (int i = 0; i < records.size(); i++) {
                    Map<String, String> r = records.get(i);
                    // 格式化电话（可选）
                    String phone = r.get("phone");
                    String maskedPhone = phone != null && phone.length() >= 7 ?
                            phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4) : phone;

                    System.out.printf("%d. 领养人：%s | 宠物：%s（%s）| 电话：%s | 领养时间：%s%n",
                            i + 1,
                            r.get("name"),
                            r.get("petName"),
                            r.get("species"),
                            maskedPhone,
                            r.get("date")
                    );
                }
            }
        } catch (SQLException e) {
            System.err.println("查询领养记录失败：" + e.getMessage());
        }
    }
    private static void handleAddPet(PetManager manager, Scanner scanner) {
        System.out.println("\n--- 添加新宠物 ---");
        if (!adminAuthenticated) {
            System.out.println("请先验证管理员身份：");
            System.out.print("用户名：");
            String user = scanner.nextLine().trim();
            System.out.print("密码：");
            String pwd = scanner.nextLine().trim();

            if ("zxl".equals(user) && "20031125".equals(pwd)) {
                adminAuthenticated = true;
                System.out.println("验证成功！\n");
            } else {
                System.out.println("用户名或密码错误！\n");
                return;
            }
        }

        System.out.print("请输入宠物名字：");
        String name = scanner.nextLine().trim();
        if (name.isEmpty()) {
            System.out.println("宠物名字不能为空！\n");
            return;
        }

        System.out.print("请输入宠物种类（如：狗、猫、仓鼠）：");
        String species = scanner.nextLine().trim();
        if (species.isEmpty()) {
            System.out.println("种类不能为空！\n");
            return;
        }

        System.out.print("请输入品种（如：金毛、英短、仓鼠等）：");
        String breed = scanner.nextLine().trim();

        System.out.print("请输入年龄（≥0）：");
        int age = getIntInput(scanner);
        if (age < 0) {
            System.out.println("年龄不能为负数！\n");
            return;
        }

        System.out.print("请输入价格（≥0）：");
        int price = getIntInput(scanner);
        if (price < 0) {
            System.out.println(" 价格不能为负数！\n");
            return;
        }

        System.out.print("请输入宠物描述（如：性格温顺、爱拆家等）：");
        String description = scanner.nextLine().trim();

        try {
            manager.addPet(name, species, breed, age, price, description);
            System.out.println("宠物 \"" + name + "\" 添加成功！状态：可领养\n");
        } catch (SQLException e) {
            System.err.println("添加失败：" + e.getMessage() + "\n");
        }
    }

    private static void handleUpdatePet(PetManager manager, Scanner scanner) {
        if (!adminAuthenticated) {
            System.out.println("🔒 请先验证管理员身份：");
            System.out.print("用户名：");
            String user = scanner.nextLine().trim();
            System.out.print("密码：");
            String pwd = scanner.nextLine().trim();

            if ("zxl".equals(user) && "20031125".equals(pwd)) {
                adminAuthenticated = true;
                System.out.println("✅ 验证成功！\n");
            } else {
                System.out.println("❌ 用户名或密码错误！\n");
                return;
            }
        }

        System.out.print("请输入要修改的宠物名字：");
        String petName = scanner.nextLine().trim();

        if (petName.isEmpty()) {
            System.out.println("宠物名字不能为空！");
            return;
        }

        PetSelect selectService = new PetSelect();
        try {
            List<Pet> pets = selectService.getPetByName(petName);
            if (pets.isEmpty() || !pets.get(0).isAvailable()) {
                System.out.println("❌ 宠物不存在、已被领养，或不可修改！");
                return;
            }

            Pet current = pets.get(0);
            System.out.println("\n--- 当前信息 ---");
            System.out.println(current);
            System.out.println("---------------------");

            System.out.println("\n👉 留空表示不修改当前值");
            System.out.print("新种类（当前：" + current.getSpecies() + "）：");
            String species = scanner.nextLine().trim();
            if (species.isEmpty()) species = current.getSpecies();

            System.out.print("新品种（当前：" + current.getBreed() + "）：");
            String breed = scanner.nextLine().trim();
            if (breed.isEmpty()) breed = current.getBreed();

            System.out.print("新年龄（当前：" + current.getAge() + "）：");
            String ageStr = scanner.nextLine().trim();
            int age = ageStr.isEmpty() ? current.getAge() : Integer.parseInt(ageStr);
            if (age < 0) {
                System.out.println("年龄不能为负数！");
                return;
            }

            System.out.print("新价格（当前：" + current.getPrice() + "）：");
            String priceStr = scanner.nextLine().trim();
            double price = priceStr.isEmpty() ? current.getPrice() : Double.parseDouble(priceStr);
            if (price < 0) {
                System.out.println("价格不能为负数！");
                return;
            }

            System.out.print("新描述（当前：" + current.getDescription() + "）：");
            String description = scanner.nextLine().trim();
            if (description.isEmpty()) description = current.getDescription();

            manager.updatePet(petName, species, breed, age, price, description);
            System.out.println("✅ 宠物 [" + petName + "] 信息修改成功！");
        } catch (NumberFormatException e) {
            System.out.println("❌ 年龄或价格格式错误，请输入数字！");
        } catch (SQLException e) {
            System.err.println("❌ 修改失败：" + e.getMessage());
        }
    }
}
